package linces

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
)

// 填充数据
func pad(src []byte, blockSize int) []byte {
	padding := blockSize - len(src)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(src, padtext...)
}

// 去掉填充
func unpad(src []byte) ([]byte, error) {
	length := len(src)
	if length == 0 {
		return nil, fmt.Errorf("input data is empty")
	}
	unpadding := int(src[length-1])
	if unpadding > length {
		return nil, fmt.Errorf("padding size error")
	}
	return src[:(length - unpadding)], nil
}

// 加密
func encrypt(plaintext, key []byte) (string, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	// 填充数据
	plaintext = pad(plaintext, block.BlockSize())

	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}

	// 使用 CBC 模式进行加密
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
	return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func GenerateAuthCode(machineCode string, AesKey []byte) string {
	// 生成授权码（加密）
	authCode, err := encrypt([]byte(machineCode), AesKey)
	if err != nil {
		fmt.Println("Error encrypting:", err)
		return ""
	}
	return authCode
}
